package com.bos.realms;

import com.bos.domian.system.Permission;
import com.bos.domian.system.Role;
import com.bos.domian.system.User;
import com.bos.service.PermsService;
import com.bos.service.RolesService;
import com.bos.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author misterWei
 * @create 2018年12月23号:21点27分
 * @mailbox mynameisweiyan@gmail.com
 */
public class UserRealmAuthentication extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private RolesService rolesService;
    @Autowired
    private PermsService permsService;
    /**
     *  统一 授权管理操作
     * */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
          //授权管理
        SimpleAuthorizationInfo simpleAuthenticationInfo = new SimpleAuthorizationInfo();

        //获取当前用户查询当前用户的角色,以及权限
        User user = (User) principalCollection.getPrimaryPrincipal();
        List<Role> byUserRole = rolesService.findByUser(user.getId());
        for (Role role : byUserRole) {
            simpleAuthenticationInfo
                    .addRole(role.getKeyword());
        }

        List<Permission> byUserPermission = permsService.findByUser(user.getId());
        for (Permission permission : byUserPermission) {
            simpleAuthenticationInfo.addStringPermission(permission.getKeyword());
        }
        return simpleAuthenticationInfo;
    }


    /**
     *  统一登陆管理认证操作
     * */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        User user = userService.findByUserName(username);
        if (user == null) {
            return null;
        }
        return  new SimpleAuthenticationInfo(user,user.getPassword(),getName());

    }
}
